"""
Authentication API Routes
Environment-aware authentication endpoints
"""

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel
from typing import Optional

from app.core.security import get_current_user, create_access_token

router = APIRouter()
security = HTTPBearer(auto_error=False)


class AuthResponse(BaseModel):
    """Authentication response model"""
    success: bool
    user: Optional[dict] = None
    token: Optional[str] = None
    message: Optional[str] = None


class LoginRequest(BaseModel):
    """Login request model (simplified for development)"""
    username: Optional[str] = None
    password: Optional[str] = None


@router.post("/login", response_model=AuthResponse)
async def login(
    request: LoginRequest,
    credentials: Optional[HTTPAuthorizationCredentials] = Depends(security)
):
    """
    Login endpoint - environment aware
    In development: always succeeds with default user
    In production: requires valid token in Authorization header
    """
    try:
        # Get current user based on environment
        if credentials:
            user = get_current_user(f"Bearer {credentials.credentials}")
        else:
            user = get_current_user(None)

        # Create access token
        token = create_access_token(data={"sub": user["user_id"]})

        return AuthResponse(
            success=True,
            user=user,
            token=token,
            message="Authentication successful"
        )

    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Authentication failed",
            headers={"WWW-Authenticate": "Bearer"},
        )


@router.get("/me", response_model=AuthResponse)
async def get_current_user_info(
    credentials: Optional[HTTPAuthorizationCredentials] = Depends(security)
):
    """
    Get current user information
    Environment-aware authentication
    """
    try:
        # Extract token from credentials
        token = credentials.credentials if credentials else None
        authorization = f"Bearer {token}" if token else None

        user = get_current_user(authorization)

        return AuthResponse(
            success=True,
            user=user,
            message="User information retrieved successfully"
        )

    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Could not validate credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )


@router.post("/validate", response_model=AuthResponse)
async def validate_token(
    credentials: Optional[HTTPAuthorizationCredentials] = Depends(security)
):
    """
    Validate token and return user information
    """
    try:
        token = credentials.credentials if credentials else None
        authorization = f"Bearer {token}" if token else None

        user = get_current_user(authorization)

        return AuthResponse(
            success=True,
            user=user,
            token=token,
            message="Token is valid"
        )

    except Exception as e:
        return AuthResponse(
            success=False,
            message=f"Token validation failed: {str(e)}"
        )


@router.post("/refresh", response_model=AuthResponse)
async def refresh_token(
    credentials: HTTPAuthorizationCredentials = Depends(security)
):
    """
    Refresh access token
    """
    try:
        # Validate current token
        user = get_current_user(f"Bearer {credentials.credentials}")

        # Create new token
        new_token = create_access_token(data={"sub": user["user_id"]})

        return AuthResponse(
            success=True,
            user=user,
            token=new_token,
            message="Token refreshed successfully"
        )

    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Could not refresh token",
            headers={"WWW-Authenticate": "Bearer"},
        )